package com.yunxin.core.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.core.application.command.page.WeightPageCommand;
import com.yunxin.core.application.service.SysTeamWeightService;
import com.yunxin.core.domain.model.weight.*;
import com.yunxin.core.infra.persistence.mapper.weight.SysTeamWeightMapper;
import com.yunxin.core.infra.persistence.mapper.weight.SysTeamWeightProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author Administrator
*/
@Service
public class SysTeamWeightServiceImpl extends ServiceImpl<SysTeamWeightMapper, SysTeamWeight> implements SysTeamWeightService {

    @Autowired
    private SysTeamWeightProductMapper sysTeamWeightProductMapper;

    @Override
    public IPage<SysTeamWeightDto> getTeamWeightPage(WeightPageCommand command) {
        Page<SysTeamWeightDto> Page = new Page<>(command.getPageNum(), command.getPageSize());
        return baseMapper.getTeamWeightPage(Page, command).convert(x->{
            List<SysTeamWeightProduct> products = sysTeamWeightProductMapper.selectList(new QueryWrapper<SysTeamWeightProduct>()
                    .eq("weight_id", x.getId())
                    .eq("team_id", x.getTeamId()));
            x.setSysTeamWeightProduct(products);
            return x;
        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveTeamWeigh(SysTeamWeightDto command) {
        checkTeamWeight(command);
        // 新增团队权重
        SysTeamWeight teamWeight = new SysTeamWeight();
        BeanUtil.copyProperties(command,teamWeight);
        teamWeight.setIsDel(SysTeamWeight.ON);
        teamWeight.setStatus(SysTeamWeight.ON);
        teamWeight.setCreateTime(new Date());
        try {
            baseMapper.insert(teamWeight);
        } catch (Exception e) {
            throw new BusinessException("添加团队权重信息异常");
        }
        // 检查团队分发占比
        checkTeamDistribute(command);
        try {
            command.getSysTeamWeightProduct().forEach(x->{
                SysTeamWeightProduct weightProduct = new SysTeamWeightProduct();
                BeanUtil.copyProperties(x,weightProduct);
                weightProduct.setWeightId(teamWeight.getId());
                weightProduct.setTeamId(command.getTeamId());
                sysTeamWeightProductMapper.insert(weightProduct);
            });
        } catch (Exception e) {
            throw new BusinessException("添加团队分发占比异常");
        }

        return true;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editTeamWeight(SysTeamWeightDto command) {
        checkTeamWeight(command);
        try {
            SysTeamWeight teamWeight = new SysTeamWeight();
            BeanUtil.copyProperties(command,teamWeight);
            teamWeight.setUpdateTime(new Date());
            baseMapper.updateById(teamWeight);
        } catch (Exception e) {
            throw new BusinessException("修改团队权重信息异常");
        }
        checkTeamDistribute(command);
        // 删除原有的产品占比
        sysTeamWeightProductMapper.delete(new QueryWrapper<SysTeamWeightProduct>()
                .eq("team_id",command.getTeamId()));
        // 添加新的产品占比
        try {
            command.getSysTeamWeightProduct().forEach(x->{
                SysTeamWeightProduct weightProduct = new SysTeamWeightProduct();
                BeanUtil.copyProperties(x,weightProduct);
                weightProduct.setWeightId(command.getId());
                weightProduct.setTeamId(command.getTeamId());
                sysTeamWeightProductMapper.insert(weightProduct);
            });
        } catch (Exception e) {
            throw new BusinessException("修改团队分发占比异常");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTeamWeight(SysWeightDelete command) {
        command.getIds().forEach(this::accept);
        return true;
    }


    @Override
    public Boolean weightSwitch(SysTeamWeight command) {
        // 先查
        SysTeamWeight weight = baseMapper.selectOne(new QueryWrapper<SysTeamWeight>().eq("id", command.getId()));
        if(Objects.isNull(weight)){
            throw new BusinessException("权重不存在");
        }
        weight.setStatus(command.getStatus());
        try {
            baseMapper.updateById(weight);
        } catch (Exception e) {
            throw new BusinessException("修改团队权重开关异常");
        }
        return true;
    }

    @Override
    public List<SysTeamWeightProductDto> getDistributeInfo(Integer teamId, Integer weightId) {
        return sysTeamWeightProductMapper.getDistributeInfo(teamId,weightId);
    }


    private void accept(Integer id) {
        // 先查
        SysTeamWeight weight = baseMapper.selectOne(new QueryWrapper<SysTeamWeight>().eq("id", id));
        if(Objects.isNull(weight)){
            throw new BusinessException("权重不存在");
        }
        weight.setIsDel(SysTeamWeight.OFF);
        weight.setUpdateTime(new Date());
        try {
            // 同步删除产品分发占比
            sysTeamWeightProductMapper.delete(new QueryWrapper<SysTeamWeightProduct>()
                    .eq("team_id", weight.getTeamId())
                    .eq("weight_id", weight.getId()));

            baseMapper.updateById(weight);
        } catch (Exception e) {
            throw new BusinessException("删除团队权重信息异常");
        }

    }


    private void checkTeamDistribute(SysTeamWeightDto command) {
        // 新增团队产品分发占比
        List<SysTeamWeightProduct> teams = sysTeamWeightProductMapper.selectList(new QueryWrapper<SysTeamWeightProduct>()
                .eq("team_id", command.getTeamId()));
        if(!teams.isEmpty() && !Objects.equals(teams.get(0).getWeightId(), command.getId())){
            throw new BusinessException("该团体已存在分发产品占比配置");
        }
    }

    private void checkTeamWeight(SysTeamWeightDto command) {
        // 判断所选团队是否已经存在权重
        SysTeamWeight team = baseMapper.selectOne(new QueryWrapper<SysTeamWeight>()
                .eq("is_del", SysTeamWeight.ON)
                .eq("team_id", command.getTeamId()));
        if(Objects.nonNull(team)){
            if(command.getId()!=null){
                if(!command.getId().equals(team.getId())){
                    throw new BusinessException("该团队不能重复配置权重");
                }
            }
            else {
                throw new BusinessException("该团队不能重复配置权重");
            }

        }
    }
}




